<script setup lang="ts">
import { addApi, deleteApi, getListApi, updateApi } from "@/apis/role";
import type { SysRole, SysRoleList } from "@/apis/role/RoleModel";
import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import { ElMessage, type FormInstance } from "element-plus";
import { nextTick, onMounted, reactive, ref } from "vue";
import useInstance from "@/hooks/useInstance";
import AssignTree from "./AssignTree.vue";
//获取全局实例
const { global } = useInstance();
const dialog = useDialog().dialog;
const searchForm = ref<FormInstance>();
const tableList = ref<SysRole[]>([]);
const total = ref<number>(0);
const tags = ref("");
const addRef = ref<FormInstance>();
const searchPaparm = reactive<SysRoleList>({
  currentPage: 1,
  pageSize: 2,
  roleName: "",
});
const getList = async () => {
  let res = await getListApi(searchPaparm);
  if (res && res.code == 200) {
    tableList.value = res.data.records;
    total.value = res.data.total;
  }
};
const assignTree = ref();

const handleSubmit = () => {
  searchPaparm.roleName = searchPaparm.roleName.trim();
  searchPaparm.currentPage = 1;
  getList();
};
const handleReset = () => {
  searchForm.value?.resetFields();
  getList();
};
const handleAdd = () => {
  // 清空表单
  addRef.value?.resetFields();
  tags.value = "0";
  dialog.visible = true;
};

// 新增角色
const addModel = reactive<SysRole>({
  id: "",
  name: "",
  description: "",
});
const rules = {
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
  ],
  description: [
    { required: true, message: "请输入角色描述", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
};
const commit = () => {
  addRef.value?.validate(async (valid) => {
    if (valid) {
      let res = null;
      if (tags.value == "0") {
        res = await addApi(addModel);
      } else {
        res = await updateApi(addModel);
      }
      if (res && res.code == 200) {
        ElMessage.success(res.msg);
        // 关闭弹框
        dialog.visible = false;
        getList();
      }
    } else {
      console.log("提交失败");
    }
  });
};
const handleEdit = (row: SysRole) => {
  tags.value = "1";
  dialog.title = "编辑角色";
  dialog.visible = true;
  nextTick(() => {
    Object.assign(addModel, row);
  });
  addRef.value?.resetFields();
};
const handleDelete = async (id: string) => {
  const confim = await global.$myconfig("确认删除吗?");
  console.log(confim);
  if (confim) {
    let res = await deleteApi(id);
    if (res && res.code == 200) {
      ElMessage.success(res.msg);
      getList();
    } else {
      ElMessage.error(res.msg);
    }
  }
};

onMounted(() => {
  getList();
});
const handleSizeChange = (val: number) => {
  searchPaparm.pageSize = val;
  getList();
};
const handleCurrentChange = (val: number) => {
  searchPaparm.currentPage = val;
  getList();
};
const handleAssign = (row: SysRole) => {
  assignTree.value.show(row.id, row.name);
};
</script>

<template>
  <el-main>
    <!-- 搜索框 -->
    <el-form
      inline
      class="demo-form-inline"
      :model="searchPaparm"
      ref="searchForm"
      label-width="80px"
      size="defalut"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input
          v-model="searchPaparm.roleName"
          placeholder="请输入关键字"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleSubmit"
          >查询</el-button
        >
        <el-button @click="handleReset" icon="Close" type="danger"
          >重置</el-button
        >
        <el-button @click="handleAdd" icon="Plus" type="success">
          新增</el-button
        >
      </el-form-item>
    </el-form>
    <SysDialog
      :title="dialog.title"
      :visible="dialog.visible"
      :width="dialog.width"
      :height="dialog.height"
      @onClose="dialog.visible = false"
      @onConfirm="commit"
    >
      <template v-slot:content>
        <el-form :model="addModel" ref="addRef" :rules="rules" size="default">
          <el-form-item label="角色名称" prop="name">
            <el-input
              style="width: 300px"
              placeholder="请输入角色名称"
              v-model="addModel.name"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input
              style="width: 300px"
              type="textarea"
              placeholder="请输入角色描述"
              v-model="addModel.description"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
    </SysDialog>
    <AssignTree ref="assignTree" />
    <!-- el-table -->
    <el-table :data="tableList" style="width: 100%" border fit>
      <el-table-column
        label="角色名称"
        prop="name"
        width="200px"
      ></el-table-column>
      <el-table-column
        label="角色描述"
        prop="description"
        width="200px"
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        width="200px"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        prop="updateTime"
        width="200px"
      ></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" @click="handleEdit(scope.row)" icon="Edit"
            >编辑</el-button
          >
          <el-button
            type="success"
            @click="handleAssign(scope.row)"
            icon="UserFilled"
            >分配权限</el-button
          >
          <el-button
            type="danger"
            @click="handleDelete(scope.row.id)"
            icon="Close"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 20px; display: flex; justify-content: center"
      v-model:current-page="searchPaparm.currentPage"
      v-model:page-size="searchPaparm.pageSize"
      :page-sizes="[2, 4, 6, 8]"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="mt-4"
      background
    />
  </el-main>
</template>

<style scoped></style>
